from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.urls import reverse
from core.models import Notification
from core.forms import NotificationForm
from core.utils import log_operation

@login_required
def notification_list(request):
    """通知列表视图，显示当前用户的所有通知"""
    # 获取当前用户的所有通知
    notifications = Notification.objects.filter(receiver=request.user).order_by('-created_at')
    
    # 将未读通知标记为已读
    unread_notifications = notifications.filter(is_read=False)
    if unread_notifications.exists():
        unread_notifications.update(is_read=True)
        # 记录操作日志
        log_operation(
            user=request.user,
            operation_type='VIEW_NOTIFICATIONS',
            content=f'查看了{unread_notifications.count()}条新通知',
            request=request
        )
    
    return render(request, 'notification/notification_list.html', {
        'notifications': notifications,
        'title': '我的通知'
    })

@login_required
def send_notification(request):
    """发送通知视图"""
    # 检查用户是否有权限发送通知
    from core.models import UserRoleAssignment
    user_roles = UserRoleAssignment.objects.filter(user=request.user).values_list('role__name', flat=True)
    if not any(role in ['principal', 'grade_leader', 'homeroom_teacher'] for role in user_roles):
        messages.error(request, '您没有发送通知的权限')
        return redirect('core:index')
    
    if request.method == 'POST':
        form = NotificationForm(request.POST, sender=request.user)
        if form.is_valid():
            notification = form.save()
            # 记录操作日志
            log_operation(
                user=request.user,
                operation_type='SEND_NOTIFICATION',
                content=f'发送通知: {notification.title}',
                request=request
            )
            messages.success(request, '通知发送成功')
            return redirect('core:notification_list')
    else:
        form = NotificationForm(sender=request.user)
    
    return render(request, 'notification/send_notification.html', {
        'form': form,
        'title': '发送通知'
    })

@login_required
def notification_detail(request, pk):
    """通知详情视图"""
    notification = get_object_or_404(Notification, pk=pk, receiver=request.user)
    
    # 如果通知未读，则标记为已读
    if not notification.is_read:
        notification.is_read = True
        notification.save()
        # 记录操作日志
        log_operation(
            user=request.user,
            operation_type='VIEW_NOTIFICATION_DETAIL',
            content=f'查看通知详情: {notification.title}',
            request=request
        )
    
    return render(request, 'notification/notification_detail.html', {
        'notification': notification,
        'title': notification.title
    })

@login_required
def delete_notification(request, pk):
    """删除通知视图"""
    notification = get_object_or_404(Notification, pk=pk, receiver=request.user)
    notification.delete()
    # 记录操作日志
    log_operation(
        user=request.user,
        operation_type='DELETE_NOTIFICATION',
        content=f'删除通知: {notification.title}',
        request=request
    )
    messages.success(request, '通知已删除')
    return redirect('core:notification_list')